import os
import numpy as np
import SimpleITK as sitk

def load_dicom(dir_path):
    #初始化SimpleITK的序列读取器
    reader = sitk.ImageSeriesReader()
    # 利用读取器得到目录下所包含的序列ID，比如图中的CT WB 5.0 B31f、PET WB (AC)和ThorRoutine 2.0 B40f
    series_IDs = reader.GetGDCMSeriesIDs(dir_path)
    file_reader = sitk.ImageFileReader()
    # print(series_IDs)
    result = []
    if series_IDs:
        for series in series_IDs:
            series_file_names =  reader.GetGDCMSeriesFileNames(dir_path, series)
            # 根据一个单张的dcm文件，读取这个series的metedata，即可以获取这个序列的描述符
            file_reader.SetFileName(series_file_names[0])
            file_reader.ReadImageInformation()
            series_description = file_reader.GetMetaData("0008|103e") # 序列的描述符，为CT WB 5.0 B31f、PET WB (AC)和ThorRoutine 2.0 B40f
            dicom_itk = sitk.ReadImage(series_file_names)
            print("正在保存序列：%s" % series_description)
            result.append([series_description, dicom_itk])
            # save_path = os.path.join(dir_path, series_description + ".nii.gz")
            # sitk.WriteImage(dicom_itk, save_path)
    return result 


def load_single_modality_dicom(dir_path):
    #初始化SimpleITK的序列读取器
    
    reader = sitk.ImageSeriesReader()
    # 利用读取器得到目录下所包含的序列ID，比如图中的CT WB 5.0 B31f、PET WB (AC)和ThorRoutine 2.0 B40f
    series_IDs = reader.GetGDCMSeriesIDs(dir_path)
    file_reader = sitk.ImageFileReader()

    assert len(series_IDs) == 1
    series = series_IDs[0]
   
    series_file_names =  reader.GetGDCMSeriesFileNames(dir_path, series)
    # 根据一个单张的dcm文件，读取这个series的metedata，即可以获取这个序列的描述符
    file_reader.SetFileName(series_file_names[0])
    file_reader.ReadImageInformation()
    series_description = file_reader.GetMetaData("0008|103e") # 序列的描述符，为CT WB 5.0 B31f、PET WB (AC)和ThorRoutine 2.0 B40f
    # print(f"出生日期：{file_reader.GetMetaData('0010|0030')}")
    # print(f"检查日期：{file_reader.GetMetaData('0008|0020')}")
    dicom_itk = sitk.ReadImage(series_file_names)
    print("正在保存序列：%s" % series_description)
    return [series_description, dicom_itk]


if __name__ == "__main__":
    result = load_dicom("./data/BAI_YUE_BIN")
    print(result)